/**
 * @file 登录
 * @module music/service/login
 * @author 月落 <yueluo.yang@qq.com>
 */

/**
 * @requires wx-server-sdk - 云函数请求库
 * @requires axios - 网络请求库
 * @requires qs - 参数序列化
 * @requires music/config - 接口配置
 */
const cloud = require('wx-server-sdk'),
      axios = require('axios').default,
      qs = require('qs'),
      config = require('../config/config');

cloud.init();

/**
 * @description 登录
 * @param {string} phone - 手机号 
 * @param {string} password - 密码
 * @returns {object} 
 */
module.exports = async ({ phone, password }) => {
  const { data } = await axios({
    method: 'GET',
    url: `${config.musicDomain}/login/cellphone?${qs.stringify({ phone, password })}`
  });
  const { code, token } = data;

  if (code === 200) {
    const { OPENID } = cloud.getWXContext();

    return {
      code: 0,
      message: 'login success.',
      data: {
        d_t: token,
        openid: OPENID
      }
    }
  } else {
    return {
      code: -1,
      message: 'login failed.',
      data: {}
    }
  }
}